  // 引入cluster模块，用于创建子进程，实现多核CPU的并行处理
const cluster = require('cluster');
const {logger,httpLogger,log } = require('./src/config/log4js');
// 引入os模块，用于获取系统信息，如CPU核数
const os = require('os');
if (cluster.isMaster){
  log.info(`main process id:${process.pid}`)
  for (var i = 0, n = os.cpus().length; i < n; i += 1) {
    worker=cluster.fork(); // 创建子进程
    log.debug(` 创建子进程${JSON.stringify(worker)}`)
  }

  // 监听SIGINT信号，通常在用户按下Ctrl+C时触发
  process.on('SIGINT', (signal) => logger.warn(`'Received: SIGINT'${signal}`));

  // 监听进程退出事件，执行清理操作
  process.on('exit', () => {
    logger.warn("process.exit() method is called in ", process.pid);
   
  });

  // 监听子进程的listening事件，当子进程开始监听端口时触发
  cluster.on('listening', function (worker, address) {
    log.info(`A worker ${worker.id} is now connected to `);
  });

  // 监听子进程的online事件，当子进程上线时触发
  cluster.on('online', function (worker) {
    
    log.info(`Worker: ${worker.process.pid} is online'`);
  });

  // 监听子进程的exit事件，当子进程退出时触发
  cluster.on('exit', function (worker, code, signal) {
    logger.error(`'Worker  ${worker.process.pid} died with code:  ${code} , and signal: ${signal}`);
    
    log.info('Starting a new worker');
    cluster.fork(); // 重新创建一个子进程
  });
}else{
  const express = require('express');
  const session = require('express-session')
  const app = express()
  const cookieParser = require('cookie-parser');
  const { authMiddleware } = require('./middleware');
  const {routeContainer}=require('./src/router')
  
 
  app.use(httpLogger)
  app.use(cookieParser());
  app.use(session({
     secret: "sefgshgkyujb",
      resave: false,
      saveUninitialized: true,
      cookie: ('name', 'value',{maxAge:  15*60*60*1000,secure: false})
  })); 
  app.use(express.static('site'))
  app.use(express.json()) // for parsing application/json
  app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

// 自定义中间件 
// app.use(authMiddleware); 
// 路径映射配置 
const routeMapping = {
  '/api/v3/auth': routeContainer.authRouter,
  '/api/v3/test': routeContainer.test 
};
 
// 动态挂载路由 
Object.entries(routeMapping).forEach(([path,  router]) => {
  app.use(path,  router);
});

// 错误处理中间件 
class ApiError extends Error {
  constructor(status, code, message) {
    super(message);
    this.status  = status;
    this.code  = code;
  }
}
 
// 错误标准化中间件 
app.use((err,  req, res, next) => {
  if (err instanceof ApiError) {
    return res.status(err.status).json({ 
      code: err.code, 
      message: err.message, 
      timestamp: new Date().toISOString(),
      traceId: req.traceId  // 全链路追踪ID 
    });
  }
});
app.use((req,  res, next) => {
  res.status(404).json({code:404,msg:`请求的资源${req.url}不存在！`})
}); 
  const port = 8082
  app.listen(port, () => {
    logger.info(`express server listen at http://localhost:${port},pid=${process.pid}`)
  })
}